//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package main

import (
	"bytes"
	"context"
	"fmt"
	"io"
	"os"
	"strings"

	"atomgit.com/openlinksaas-org/api-server/utils"
	"atomgit.com/openlinksaas-org/proto-gen-go.git/fs_api"
)

func saveFile(dirList []string, fileName string, data []byte) error {
	dirPath := strings.Join(dirList, string(os.PathSeparator))
	err := os.MkdirAll(dirPath, 0700)
	if err != nil {
		return err
	}
	filePath := strings.Join([]string{dirPath, fileName}, string(os.PathSeparator))
	err = os.WriteFile(filePath, data, 0600)
	if err != nil {
		return err
	}
	return nil
}

func getFileData(ctx context.Context, fsId, fileId string) ([]byte, error) {
	if globalServCfg == nil {
		return nil, fmt.Errorf("niss config")
	}
	conn, err := utils.ConnGrpc(globalServCfg.ClientCfg.ServerAddr)
	if err != nil {
		return nil, err
	}
	defer conn.Close()

	client := fs_api.NewFsApiClient(conn)
	s, err := client.ReadFile(ctx, &fs_api.ReadFileRequest{
		SessionId: "",
		FsId:      fsId,
		FileId:    fileId,
	})
	if err != nil {
		return nil, err
	}
	buf := &bytes.Buffer{}
	for {
		res, err := s.Recv()
		if err == io.EOF {
			break
		}
		if err != nil {
			return nil, err
		}
		buf.Write(res.Data)
	}
	return buf.Bytes(), nil
}
